package com.mz361.stdapi.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.mz361.common.utils.*;
import com.mz361.component.jwt.config.properties.JwtProjectProperties;
import com.mz361.component.jwt.utlis.JwtUtil;
import com.mz361.modules.system.domain.*;
import com.mz361.modules.system.service.*;
import com.mz361.stdapi.service.SignInService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author niceale
 * @ date 2024/04/26
 */
@Service
@Slf4j
public class SignInServiceImpl implements SignInService {


    @Autowired
    RedisUtil redisUtil;
    @Autowired
    private UserService userService;
    @Autowired
    QueryCompanyUtil queryCompanyUtil;
    @Autowired
    SendMessageUtil sendMessageUtil;
    @Autowired
    private CMemberService cMemberService;
    @Autowired
    private CSourceService cSourceService;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private JwtProjectProperties properties;
    @Autowired
    private OrderUserService orderUserService;

    @Override
    public boolean sendCode(String phone, String type) {

        if (redisUtil.exists("VerifyMessage:" + type + ":" + phone)) {
            return false;
        }
        String code = CaptchaUtil.generatedcode(4);
        sendMessageUtil.sendMsg(phone, code, type);
        redisUtil.setexValue("VerifyMessage:" + type + ":" + phone, 120, code);
        return true;
    }

    @Override
    public String verifyPhone(String phone) {
        CMember cMember = cMemberService.getByPhone(phone);
        if (null != cMember) {
            if (null != cMember.getCompanyId() || cMember.getType().equals("1")) {
                return "2";
            } else {
                return "1";
            }
        }
        return "0";
    }

    @Override
    public User getByInviteCode(String inviteCode) {
        return userService.getByInviteCode(inviteCode);
    }

    @Override
    public CMember getByUserId(String userId) {
        return cMemberService.getById(Long.valueOf(userId));
    }

    @Override
    public CMember getByPhone(String phone) {
        return cMemberService.getByPhone(phone);
    }

    @Override
    public boolean verify(String phone, String code, String type) {
        if (redisUtil.exists("VerifyMessage:" + type + ":" + phone)) {
            String msg = redisUtil.getValue("VerifyMessage:" + type + ":" + phone);
            return msg.equals(code);
        } else {
            return false;
        }
    }

    @Override
    public CMember fistSingIn(String phone, String password, String type) {

        CMember cMember = new CMember();
        cMember.setNickname("mz361_" + StringUtil.md5(phone));
        cMember.setName("mz361_" + phone);
        cMember.setPhone(phone);
        String salt = EncryptUtil.getRandomSalt();
        String encrypt = EncryptUtil.encrypt(password, salt);
        cMember.setInviteCode(EncryptUtil.getRandomSalt());
        cMember.setPassword(encrypt);
        cMember.setSalt(salt);
        cMember.setType(type);// 用户类型
        cMember.setCreateDate(new Date());
        cMember.setUpdateDate(new Date());
        cMember = cMemberService.save(cMember);
        return cMember;
    }

    @Override
    public CMember findPassword(String phone, String password) {
        CMember cMember = cMemberService.getByPhone(phone);
        if (null != cMember) {
            String salt = EncryptUtil.getRandomSalt();
            String encrypt = EncryptUtil.encrypt(password, salt);
            cMember.setPassword(encrypt);
            cMember.setSalt(salt);
            cMember.setUpdateDate(new Date());
            cMember = cMemberService.save(cMember);
            return cMember;
        }
        return null;
    }

    @Override
    public void delMessge(String phone) {
        redisUtil.del("VerifyMessage:" + phone);
    }

    @Override
    public JSONObject getLoginData(String phone, CMember cMember) {
        List<OrderUser> orderUsers = orderUserService.getOrderUsersByCompanyId(cMember.getCompanyId());
        boolean orderFlag = null != orderUsers && !orderUsers.isEmpty();
        String token = JwtUtil.getToken(phone, properties.getSecret(), properties.getExpired());
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("token", token);
        jsonObject.put("userId", cMember.getId());
        jsonObject.put("orderFlag", orderFlag);
        return jsonObject;
    }

    @Override
    public String verifyCompany(String phone, String companyName, String companyNum, User user) {
        //判断用户是否有注册申请
        CMember cMember = cMemberService.getByPhone(phone);
        if (cMember == null) {
            log.info("此号{}未发现申请注册", phone);
            return "1";
        }
        //查看是否已做过企业认证，这里有疑点，做过的企业认证的是否需要开放其他用户注册
        Company company = companyService.getByCompanyNum(companyNum);
        if (null != company) {
            log.info("此信用代码已注册：{} 企业名称：{}", companyNum, companyName);
            return "2";
        }
        String adCode, lon, lat, address, industry, companyData;
        String comName = companyName;
        // 企业信用代码检测及验证
        if (redisUtil.hexists("COMPANYDATA", companyNum)) {
            companyData = redisUtil.hGet("COMPANYDATA", companyNum);
        } else {
            companyData = queryCompanyUtil.queryCompanyData(companyNum);
            if (companyData != null) {
                if (companyData.contains("error_code") && JSONObject.parseObject(companyData).getInteger("error_code") == 0) {
                    redisUtil.hSet("COMPANYDATA", companyNum, companyData);
                }
            } else {
                log.info("企业认证失败！{} {}", companyNum, companyName);
                return "3";
            }
        }
        if (StringUtil.notEmpty(companyData) && JSONObject.parseObject(companyData).getInteger("error_code") == 0) {
            JSONObject comJSON = JSONObject.parseObject(companyData).getJSONObject("result");
            comName = comJSON.getString("companyName");
            if (!StringUtil.isEqual(comName, companyName)) {
                log.info("企业信息错误");
                return "4";
            }
            adCode = comJSON.getString("adCode");
            lon = comJSON.getString("lon");
            lat = comJSON.getString("lat");
            address = comJSON.getString("address");
            industry = comJSON.getString("industry");
            CSource cSource = cSourceService.getBySourceKey(user.getSourceKey());////获取渠道信息
            company = new Company();
            company.setCompanyName(comName);
            company.setSourceKey(user.getSourceKey());
            company.setCompanyOutId(cSource.getId());
            company.setCompanyNum(companyNum);
            company.setAreaCode(adCode);
            company.setLon(lon);
            company.setLat(lat);
            company.setAddress(address);
            company.setIndustry(industry);
            company.setInviteCode(user.getInviteCode());
            company.setCreateBy(user);
            company.setCreateDate(new Date());
            company.setUpdateDate(new Date());
            company = companyService.save(company);

            //绑定用户和企业、渠道关系
            cMember.setInviteCode(user.getInviteCode());
            cMember.setCompanyId(company.getId());
            cMember.setSourceId(cSource.getId());
            cMemberService.save(cMember);
            return "0";
        }

        return "3";

    }


}
